<template>
  <el-dialog title="上传文件" :visible.sync="option.isShow" width="800px" :lock-scroll=false @open="openHandle" @close="closeHandle">
    <el-card v-loading="loading">
      <el-upload ref="upload" :action="fileUrl" :file-list="fileList" :limit="1" :on-exceed="handleExceed" :on-change="handleChange" :on-success="successCallback" :auto-upload="false" :on-error="handleError">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" :disabled="enable" @click="submitUpload">上传到服务器</el-button>
        <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件，且不超过5MB</div>
      </el-upload>
      <el-table ref="tableData" :data='outputJSON' header-row-class-name="tableHeaderClass" border style="margin:10px 0 0 0">
        <el-table-column prop='NO' label='序号'></el-table-column>
        <el-table-column prop='坐席工号' label='坐席工号'></el-table-column>
        <el-table-column prop='姓名' label='姓名'></el-table-column>
        <el-table-column prop='班' label='班'  :formatter="dataFormat"></el-table-column>
        <el-table-column prop='组名' label='组名'  :formatter="dataFormat"></el-table-column>
        <el-table-column prop='角色' label='角色'  :formatter="dataFormat"></el-table-column>
        <el-table-column prop='坐席等级' label='坐席等级'  :formatter="dataFormat"></el-table-column>
        <el-table-column prop='受理渠道' label='受理渠道'  :formatter="dataFormat"></el-table-column>
        <el-table-column prop='人员状态' label='人员状态'  :formatter="dataFormat"></el-table-column>
        <el-table-column prop='联系方式' label='联系方式'></el-table-column>
        <el-table-column prop='邮箱' label='邮箱'></el-table-column>
        <el-table-column prop='性别' label='性别'  :formatter="dataFormat"></el-table-column>
        <el-table-column prop='登录方式' label='登录方式'  :formatter="dataFormat"></el-table-column>
      </el-table>
    </el-card>
    <span slot="footer" class="dialog-footer">
      <el-button @click="option.isShow=false" size="mini">取 消</el-button>
    </span>
  </el-dialog>
</template>
<script>
import requestYg from "@/common/utils/requestYg";
import batchAdd from "@/message/seat-manage/SeatInfoManage/batchAdd";
import getGlobalParams from "@/common/utils/getGlobalParams";
 // 班组接口
  import teamManage from "@/message/seat-manage/setaTeam/teamManage";

export default {
  props: ['option'],
  data() {
    return {
      deptMap:{},
      'mediaList': {
          '00': '电话',
          '01': '视频',
          '02': '文字',
        },
      "LOGINFLG": {
          "1": "1-密码",
          "0": "0-指纹",
        },
        "AGENTSEX": {
          "1": "1-男",
          "2": "2-女",
        },
        "STAFSTS": {
          "01": "试用",
          "02": "正式上岗"
        },
         "AGENTLEVEL": {
          "1": "1-一星",
          "2": "2-二星",
          "3": "3-三星",
          "4": "4-四星",
          "5": "5-五星",
        },
         "AGENTROLE": {
          "01": "01-普通坐席",
          "02": "02-组长",
          "03": "03-班长",
          // "04": "04-坐席主管",
          // "05": "05-坐席经理",
          // "06": "06-质检员",
          // "07": "07-质检主管",
          // "08": "08-培训师",
          // "09": "09-培训主管",
          // "10": "10-排班师",
          // "11": "11-排班主管",
          // "12": "12-知识库普通用户",
          // "13": "13-知识库管理员"
        },
        STAFSTSLIST: [{
            name: '试用',
            value: '01'
          },
          {
            name: '正式上岗',
            value: '02'
          },
        ],
      fileUrl: "",
      fileList: [],
      filepath: "",
      fileDownUrl: "",
      enable: true,
      loading: false,
      outputJSON: [],
      queryBtn: false
    };
  },
  created() {
    // 获取版本上传地址
    this.fileUrl = getGlobalParams.get("KnowledgeFileUploadAddress");
    this.filepath = getGlobalParams.get("ExcelPath");
    // this.fileDownUrl = getGlobalParams.get("KnowledgeFileDownloadAddress");
  },
  methods: {
    // 查询班
      squery() {
        this.loading = true;
        let resBody = new teamManage();
        resBody.data.OPERATION = "4";
        resBody.data.TEAMTYPE = "1";
        requestYg(resBody)
          .then(response => {
            if (response.SYS_HEAD.ReturnCode === "000000") {
              let STeamTypeList = response.RSP_BODY.struct;
              for (let i = 0; i < STeamTypeList.length; i++) {
                const element = STeamTypeList[i];
                this.deptMap[element.TEAMID] = element.TEAMNAME;
              }
              this.agentQuery();
            } else {
              this.$message({
                type: "error",
                message: "请求失败，错误码: " + response.SYS_HEAD.ReturnCode + ",错误信息: " + response.SYS_HEAD.ReturnMessage
              });
              this.STeamTypeList = [];
            }
          })
          .catch(error => {
            this.loading = false;
          })
      },
      // 查询组
      async teamQuery() {
        //debugger
        let resBody = new teamManage();
        resBody.data.OPERATION = '4'
        resBody.data.TEAMTYPE = '2'
        resBody.data.PAGEFLAG = 4
        resBody.data.CURRPAGE = 1
        resBody.data.PAGEROWNUM = 100
        // resBody.data.HTEAMID = this.form.AGENTDEP
        let response = await requestYg(resBody);
        if (response.SYS_HEAD.ReturnCode === "000000") {
          this.teamOption = response.RSP_BODY.struct
          for (let i = 0; i < this.teamOption.length; i++) {
            const element = this.teamOption[i];
            this.deptMap[element.TEAMID] = element.TEAMNAME;
          }
        } else {
          this.$message({
            type: "error",
            message: '该班下没有对应组'
          });
          this.teamOption = []
          this.form.GENTTEAM = ''
        }
      },
    dataFormat(row, column) {
        if (column.property == "坐席等级")
          return this.AGENTLEVEL[row[column.property]];
        if (column.property == "登录方式")
          return this.LOGINFLG[row[column.property]];
        if (column.property == "性别")
          return this.AGENTSEX[row[column.property]];
        // if (column.property == "ENGLEVEL")
        //   return this.ENGLEVEL[row[column.property]];
        if (column.property == "班")
          return this.deptMap[row[column.property]];
        if (column.property == "角色")
          return this.AGENTROLE[row[column.property]];
        if (column.property == "组名")
          return this.deptMap[row[column.property]];
        if (column.property == "人员状态")
          return this.STAFSTS[row[column.property]];
        if (column.property == "受理渠道")
          return this.mediaFormat(row[column.property]);
      },
      // 过滤渠道
      mediaFormat(str) {
        let value = []
        let arr = str.split('|')
        arr.forEach(item => {
          value.push(this.mediaList[item])
        })
        return value.join(',')
      },
    openHandle() {
      this.squery(); //查询班
      this.teamQuery();
      // this.initPop();
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    // 大于一个文件提示信息
    handleExceed(files, fileList) {
      this.$message.warning(`只能上传一个文件！`);
    },
    // 上传成功的回调
    async successCallback(val, file) {
      console.log(val);
      console.log("this.filepath", this.filepath);
      this.loading = true;
      let resBody = new batchAdd();
      resBody.data.FileName = file.name;
      resBody.data.FilePath = this.filepath;
      let response = await requestYg(resBody);
      this.loading = false;
      if (response.SYS_HEAD.ReturnCode == "000000") {
        console.log("===========", response.RSP_BODY);
        this.$message({
          type: "success",
          message: "文件上传成功"
        });
        this.option.isShow = false
        this.$emit("refreshTable1");
      } else {
        this.fileList = [];
        this.$message({
          type: "error",
          message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
        });
      }
    },
    handleError() {
      this.$message.warning(`文件上传失败！`);
    },
    closeHandle() {
      this.initPop();
      this.enable = true;
    },

    initPop() {
      this.outputJSON = [];
      this.queryBtn = false;
      this.fileList = [];
    },
    async downloadDemo() {
      let resBody = new download()
      resBody.data.TempType = 'Q'
      let response = await requestYg(resBody);
      if (response.SYS_HEAD.ReturnCode == "000000") {
        let res = response.RSP_BODY.RspStruct[0]
        let url = res.FILENAME
        this.downloadFile(this.fileDownUrl + '/' + url)
      } else {
        this.$message({
          type: "error",
          message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
        })
      }
      // this.downloadFile(this.fileDownUrl+'/'+'模板_导入问题.xlsx');
    },
    handleChange(file, fileList) {
      console.log("file", file);
      var vueIns = this;
      var IMPORTFILE_MAXSIZE = 1 * 5120;
      const isLt5M = file.size / 1024 < IMPORTFILE_MAXSIZE;
      //控制导入文件大小
      //判断是否有文件
      if (!file) {
        vueIns.$message({
          message: "请选择文件",
          type: 'error  '
        });
        vueIns.outputJSON = [];
        return
      }
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB!');
        vueIns.outputJSON = [];
        file = "";
        return
      }
      //判断格式
      // console.log(fileData);
      var tempArr = file.name.split(".");
      var suffix = tempArr[tempArr.length - 1];
      if (suffix != 'xls' && suffix != 'xlsx') {
        vueIns.$message({
          message: "文件格式不正确",
          type: 'error  '
        });
        vueIns.outputJSON = [];
        file = "";
        return
      }
      var reader = new FileReader();
      reader.onloadend = async function(e) {
        var data = e.target.result;
        var workbook = vueIns.XLSX.read(data, { type: 'binary' });
        var sheetObject = workbook.Sheets[workbook.SheetNames[0]];
        delete sheetObject.A1;
        var temp = JSON.parse(JSON.stringify(vueIns.XLSX.utils.sheet_to_json(sheetObject)));
        var outPutArr = [];
        temp.splice(0, 1);
        console.log("outPutArr", temp);
        for (var i = 0; i < temp.length; i++) {
          var quesContent = new Object();
          quesContent.NO = temp[i].__EMPTY;
          quesContent['坐席工号'] = temp[i].__EMPTY_1;
          quesContent['姓名'] = temp[i].__EMPTY_2;
          quesContent['班'] = temp[i].__EMPTY_3;
          quesContent['组名'] = temp[i].__EMPTY_4;
          quesContent['角色'] = temp[i].__EMPTY_5;
          quesContent['坐席等级'] = temp[i].__EMPTY_6;
          quesContent['受理渠道'] = temp[i].__EMPTY_7;
          quesContent['人员状态'] = temp[i].__EMPTY_8;
          quesContent['联系方式'] = temp[i].__EMPTY_9;
          quesContent['邮箱'] = temp[i].__EMPTY_10;
          quesContent['性别'] = temp[i].__EMPTY_11;
          quesContent['登录方式'] = temp[i].__EMPTY_12;
          // if (temp[i].__EMPTY_3) {
          //   quesContent.CHANNEL = temp[i].__EMPTY_3;
          // } else {
          //   quesContent.CHANNEL = "";
          // }
          // quesContent.ANWSERTYPE = temp[i].__EMPTY_4;
          // quesContent.ANWSERVALUE = temp[i].__EMPTY_5;
          outPutArr.push(
            quesContent
          );
        }
        if (outPutArr[0]['坐席工号'] && outPutArr[0]['姓名'] && outPutArr[0]['班'] && outPutArr[0]['组名'] && outPutArr[0]['角色']&& outPutArr[0]['坐席等级']&& outPutArr[0]['受理渠道']&& outPutArr[0]['人员状态']&& outPutArr[0]['联系方式']&& outPutArr[0]['邮箱']) {
          vueIns.outputJSON = outPutArr;
          console.log(vueIns.outputJSON);
          vueIns.queryBtn = true;
          vueIns.enable = false;
        }
        else {
          vueIns.$message({
            message: "请遵循对应格式",
            type: 'error  '
          });
          vueIns.outputJSON = [];
          return
        }
      };
      reader.readAsBinaryString(file.raw);
    }
  }
};
</script>

<style scoped>

</style>
